package controllers

import (
	"gini2p/models"
	"net/http"

	"crypto/md5"
	"encoding/hex"
	"time"

	"fmt"
	"gini2p/logger"
	"gini2p/utility"
	"math/rand"
	"strconv"

	"github.com/gin-gonic/gin"
)

type LoginForm struct {
	Username string `form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

func Login(c *gin.Context) {
	var login LoginForm
	if err := c.Bind(&login); err == nil {
		manage, err := models.GetManageByName(login.Username)
		pm := md5.New()
		pm.Write([]byte(login.Password))
		md5p := pm.Sum(nil)
		password := hex.EncodeToString(md5p)
		if err != nil || manage.Password != password {
			c.JSON(http.StatusUnprocessableEntity, gin.H{
				"status":  422,
				"message": "用户名或者密码不正确",
				"data":    []interface{}{},
			})
		} else {
			tm := md5.New()
			r := rand.New(rand.NewSource(time.Now().UnixNano()))
			rnum := strconv.Itoa(r.Intn(10000))
			now := strconv.FormatInt(time.Now().UnixNano(), 10)

			tm.Write([]byte(rnum + now))
			token := tm.Sum(nil)
			err = models.MakeNewToken(manage.Id, hex.EncodeToString(token))
			if err != nil {
				logger.Error("sql", fmt.Sprint("修改数据库token出错", err))
			}

			utility.RenewSession(c, hex.EncodeToString(token), manage.Id)

			logger.Info("app", utility.FormatLog(c, fmt.Sprint("token:", hex.EncodeToString(token), "time:", time.Now())))

			c.JSON(http.StatusOK, gin.H{
				"status":  200,
				"message": "登录成功",
				"data": map[string]string{
					"access_token": hex.EncodeToString(token),
				},
			})
		}
	} else {
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"status":  422,
			"message": "用户名或者密码不能为空",
			"data":    err.Error(),
		})
	}
}

